#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#       bp-tvmkv.py
#       
#       Copyright 2012 Bruno Paulin <brunopaulin@bpaulin.net>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.
#       
#       
import sys
import os

ext_movies = ('.avi', '.mp4')
ext_subs = ('.srt')

def main():
	## Check if mkvmerge is available
	if os.system('mkvmerge --version')!=0:
		print('mkvmerge not found, please install it')
		return(1)
		
	## Get folder to compute
	try:
		folder = sys.argv[1]
		os.chdir(folder)
	except:
		folder = os.getcwd()
	print('Folder: %s'%folder)
	
	## Get movies files
	episodes = [episode for episode 
				in os.listdir(folder) 
				if (os.path.splitext(episode)[1] in ext_movies)]
	episodes.sort()
	print('%i file(s) found'%len(episodes))
	
	## compute each episode
	for episode in episodes:
		file_video = os.path.split(episode)[1]
		print('## Episode: %s'%file_video)
		
		## Get subs files
		subs = [sub for sub
				in os.listdir(folder) 
				if (os.path.splitext(sub)[1] in ext_subs)
				and sub.count(os.path.splitext(episode)[0])>0]
		print('%i sub(s) found'%len(subs))
		
		## Create command line
		mkv = os.path.splitext(file_video)[0] + '.mkv'
		line_sub = ''.join(['"%s"'%sub for sub in subs])
		line = 'mkvmerge -q -o "%s" "%s" %s '%(mkv, file_video, line_sub)
		
		## Merging
		print('merging...')
		ok = os.system(line)
		
		## Remove files
		if ok==0:
			print('removing...')
			os.remove(episode)
			for sub in subs:
				os.remove(sub)
				
	
if __name__ == '__main__':
	main()

